package com.ehomepay.xyxeample.common.redis.config;

import com.ehomepay.xyxeample.common.redis.property.RedisProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Administrator on 2018/5/8.
 */
@Configuration
public class RedisConfig {

    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisCluster findJedisCluster(){
        String clusterNodes = redisProperties.getClusterNodes();
        if (StringUtils.isEmpty(clusterNodes)) {
            logger.error("spring.redis.zone is blank.");
            throw new IllegalArgumentException("spring.redis.clusterNodes is blank.");
        }

        String[] hosts = clusterNodes.split(",");
        Set<HostAndPort> hostAndPortSet = new HashSet<HostAndPort>();
        for(int i=0;i<hosts.length;i++){
            String host = hosts[i];
            String[] hostSplit = host.split(":");
            if(host.indexOf(":") == -1){
               throw new IllegalArgumentException("spring.redis.clusterNodes is not find 【:】,pattern ip:port.");
            }
            try {
                hostAndPortSet.add(new HostAndPort(hostSplit[0].trim(), Integer.parseInt(hostSplit[1].trim())));
            }catch (Exception e){
                logger.error("port must be a number!" , e);
            }
        }
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getPoolMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getPoolMaxWait());
        jedisPoolConfig.setMaxTotal(redisProperties.getPoolMaxActive());
        jedisPoolConfig.setMinIdle(redisProperties.getPoolMinIdle());
        jedisPoolConfig.setTestOnBorrow(redisProperties.getPoolTestOnBorrow());

        return new JedisCluster(hostAndPortSet, redisProperties.getTimeout(), redisProperties.getMaxRedirections(),jedisPoolConfig);
    }
}
